<template>
	<view class="video-list">
		<view v-if="!isNotVideo">
			<u-tabs lineColor="transparent" :list="list1" @change="handleTabChange" :current="currentTab" :activeStyle="{ color: '#FF7220', fontWeight: 'bold',transform: 'scale(1.05)'
			         }" itemStyle="padding-left: 46rpx; padding-right: 46rpx; height: 80rpx;"></u-tabs>
			<view class="list-container" v-if="currentTab == 0">
				<view class="video-item">
					<video style="width: 100%;height: 380rpx;" :src="item.resUrl" v-for="(item, index) in videoLiss"
						:key="index" autoplay></video>
				</view>
				<view class="button-group">
					<u-button text="复制视频地址" color="#F57B00" plain shape="circle"
						@click="copyText(videoLiss[0].resUrl)"></u-button>
					<u-button text="保存视频" color="#F57B00" shape="circle" @click="savevideo"></u-button>
				</view>
				<view style="margin: 40rpx;" v-if="audiolist.length>0">
					<u-button text="保存音频" color="green" shape="circle" @click="saveAudio"></u-button>
				</view>
				<view style="margin: 40rpx;">
					<u-button text="返回首页" color="green" plain shape="circle" @click="goBack"></u-button>
				</view>
			</view>
			<view class="list-container" v-if="currentTab ==1">
				<view class="video-item">
					<view class="video-info">
						<view class="video-title">{{resource.title}}</view>
					</view>
				</view>
				<view style="margin: 40rpx;">
					<u-button text="保存文案" color="#F57B00" shape="circle" @click="copyText(resource.title)"></u-button>
				</view>
			</view>
			<view class="list-container" v-if="currentTab ==2">
				<view class="video-item">
					<view class="video-info">
						<image :src="resource.pic" mode="aspectFit" style="width: 100%;height: 300rpx;"></image>
					</view>
					<view style="margin: 40rpx;">
						<u-button text="保存封面" color="#F57B00" shape="circle"
							@click="saveImage(resource.pic)"></u-button>
					</view>
				</view>
			</view>
		</view>
		<view v-else>
			<u-tabs lineColor="transparent" :list="list2" @change="handleTabChange1" :current="currentTab1"
				:activeStyle="{ color: '#FF7220', fontWeight: 'bold',transform: 'scale(1.05)'}"
				itemStyle="padding-left: 46rpx; padding-right: 46rpx; height: 80rpx;"></u-tabs>
			<view class="list-container" v-if="currentTab1 ==0">
				<view class="video-item">
					<view class="video-info">
						<view class="image-grid">
							<view v-for="(item, index) in piclist" :key="index" class="image-item">
								<image :src="item.resUrl" class="grid-image"></image>
								<u-button text="下载" color="#F57B00" shape="circle"
									@click="saveImage(item.resUrl)"></u-button>
							</view>
						</view>
					</view>
				</view>
			</view>
			<view class="list-container" v-if="currentTab1 ==1">
				<view class="video-item">
					<view class="video-info">
						<view class="video-title">{{resource.desc}}</view>
						<!-- <view class="video-title u-line-2">{{resource.desc}}</view> -->
					</view>
				</view>
				<view style="margin: 40rpx;">
					<u-button text="保存文案" color="#F57B00" shape="circle" @click="copyText(resource.desc)"></u-button>
				</view>
			</view>
		</view>

	</view>
</template>

<script>
	import {
		history_list,
		getVideoexport,
		support_list
	} from '@/api/user.js'
	export default {
		data() {
			return {
				resource: {},
				resourceList: [],
				selectedImages: {},
				currentImage: '',
				piclist: [],
				audiolist: [],
				videoLiss: [],
				videosss: [],
				list1: [{
					name: '视频',
				}, {
					name: '文案',
				}, {
					name: '封面'
				}, ],
				// 当前激活的标签索引
				currentTab: 0,
				currentTab1: 0,
				list2: [{
					name: '图库',
				}, {
					name: '文案',
				}],
				isNotVideo: true
			}
		},
		onShow() {
			console.log('资源信息', uni.getStorageSync('videoList'))
			// 页面加载时获取视频列表数据
			this.getVideoList()

		},
		methods: {
			// 获取视频列表数据
			async getVideoList() {
				const that = this
				that.resource = uni.getStorageSync('videoList')
				that.resourceList = that.resource.res
				that.piclist = []
				that.audiolist = []
				that.videoLiss = []

				if (this.resource.platform == 'douyin') {
					this.resourceList = that.resourceList.filter(item => item.resName !== 'H264');

				}
				that.resourceList.forEach(item => {
					if (item.resType == 1) { //图片
						that.piclist.push(item)
					}
					if (item.resType == 2) { //音频
						that.audiolist.push(item)
					}
					if (item.resType == 3) { //视频
						that.videoLiss.push(item)

					}

				})

				if (that.resource.platform == 'xiaohongshu' || 'goofish') {
					that.isNotVideo = that.resourceList.every(item => item.resType !== 3);
					console.log(that.isNotVideo)
				}

			},
			videoErrorCallback(e) {
				uni.showModal({
					title: '播放错误',
					content: JSON.stringify(e),
					showCancel: false
				})
			},
			// 标签切换时的处理方法
			handleTabChange(item) {
				this.currentTab = item.index
				// if (item.index === 4 && this.audiolist.length > 0) {
				// 	this.getAudioDuration()
				// }
			},
			// 标签切换时的处理方法
			handleTabChange1(item) {
				this.currentTab1 = item.index
			},
			goBack() {

				uni.redirectTo({
					url: '/pages/index/index'
				})
			},

			// 保存视频
			savevideo() {
				uni.showToast({
					title: '下载中',
					icon: 'none'
				});
				uni.downloadFile({
					url: this.videoLiss[0].resUrl,
					success: (res) => {
						if (res.statusCode === 200) {
							console.log(res, 'res.tempFilePath')
							const link = document.createElement('a');
							link.href = res.tempFilePath; // 使用临时文件路径
							link.download = 'video.mp4'; // 设置下载文件名
							document.body.appendChild(link);
							link.click();
							document.body.removeChild(link);
							uni.showToast({
								title: '下载成功',
								icon: 'success'
							});
						} else {
							console.log(res, 'res.tempFilePath')
							uni.showToast({
								title: '下载失败',
								icon: 'none'
							});
						}
					},
					fail: (err) => {
						console.error(err);
						uni.showToast({
							title: '下载失败',
							icon: 'none'
						});
					}
				});
			},
			//保存音频
			saveAudio() {
				uni.showToast({
					title: '下载中',
					icon: 'none'
				});
				uni.downloadFile({
					url: this.audiolist[0].resUrl, // 替换为音频文件的实际 URL
					success: (res) => {
						if (res.statusCode === 200) {
							console.log(res, 'res')
							const link = document.createElement('a');
							link.href = res.tempFilePath; // 使用临时文件路径
							link.download = 'audio.mp3'; // 设置下载文件名
							document.body.appendChild(link);
							link.click();
							document.body.removeChild(link);
							uni.showToast({
								title: '下载成功',
								icon: 'success'
							});
						} else {
							uni.showToast({
								title: '下载失败',
								icon: 'none'
							});
						}
					}
				});
			},
			//复制文案
			copyText(item) {
				// 判断是否为 H5 平台
				if (process.env.VUE_APP_PLATFORM === 'h5') {
					navigator.clipboard.writeText(item).then(() => {
						uni.showToast({
							title: '复制成功',
							icon: 'none'
						});
					}).catch(() => {
						uni.showToast({
							title: '复制失败',
							icon: 'none'
						});
					});
				}
			},
			getAudioDuration() {
				// 创建音频上下文
				this.innerAudioContext = uni.createInnerAudioContext();

				// 设置音频文件路径
				this.innerAudioContext.src = this.audiolist[0].resUrl;

				// 监听音频可以播放的事件
				this.innerAudioContext.onCanplay(() => {
					// 使用定时器延迟获取音频时长
					let intervalID = setInterval(() => {
						if (this.innerAudioContext.duration !== 0) {
							clearInterval(intervalID); // 清除定时器
							const duration = this.innerAudioContext.duration / 60
							this.audioDuration = duration.toFixed(2); // 保留两位小数
							console.log('音频时长：', this.audioDuration);
						}
					}, 500);
				});

				// 监听错误事件
				this.innerAudioContext.onError((err) => {
					console.error('音频加载失败：', err);
				});

				// 触发一次播放事件，以便能够获取到音频时长
				this.innerAudioContext.play();
				this.innerAudioContext.pause(); // 可以立即暂停，不影响获取到音频时长
			},
			convertToHTTPS(url) {
				// 检查 URL 是否以 http 开头
				if (url.startsWith('http://')) {
					// 替换为 https
					return url.replace('http://', 'https://');
				}
				return url; // 如果已经是 https 或其他协议，直接返回原 URL
			},

			saveImage(imageUrl) {
				console.log(this.convertToHTTPS(imageUrl));
				uni.request({
					url: this.convertToHTTPS(imageUrl),
					responseType: 'arraybuffer',
					success: (res) => {
						if (res.statusCode === 200) {
							const arrayBuffer = res.data;
							const blob = new Blob([arrayBuffer], {
								type: 'image/jpeg'
							});
							const url = URL.createObjectURL(blob);
							const a = document.createElement('a');
							a.href = url;
							a.download = imageUrl;
							a.click();
							URL.revokeObjectURL(url);
						} else {
							uni.showToast({
								title: '下载失败，状态码：' + res.statusCode,
								icon: 'none'
							});
						}
					},
					fail: (err) => {
						uni.showToast({
							title: '下载失败：' + err.errMsg,
							icon: 'none'
						});
					}
				});
			},
			//下载图片
			// saveImage(url) {
			// 	uni.showToast({
			// 		title: '下载中',
			// 		icon: 'none'
			// 	});
			// 	uni.downloadFile({
			// 		url: url, // 替换为音频文件的实际 URL
			// 		success: (res) => {
			// 			if (res.statusCode === 200) {
			// 				const link = document.createElement('a');
			// 				link.href = res.tempFilePath; // 使用临时文件路径
			// 				link.download = 'pic.jpg'; // 设置下载文件名
			// 				document.body.appendChild(link);
			// 				link.click();
			// 				document.body.removeChild(link);
			// 				uni.showToast({
			// 					title: '下载成功',
			// 					icon: 'success'
			// 				});
			// 			} else {
			// 				uni.showToast({
			// 					title: '下载失败',
			// 					icon: 'none'
			// 				});
			// 			}
			// 		}
			// 	});
			// },

			//保存封面
			downloadPic() {
				uni.showToast({
					title: '下载中',
					icon: 'none'
				});
				const secureUrl = this.convertToHTTPS(this.resource.pic);
				uni.downloadFile({
					url: secureUrl, // 替换为音频文件的实际 URL
					success: (res) => {
						if (res.statusCode === 200) {
							const link = document.createElement('a');
							link.href = res.tempFilePath; // 使用临时文件路径
							link.download = 'pic.jpg'; // 设置下载文件名
							document.body.appendChild(link);
							link.click();
							document.body.removeChild(link);
							uni.showToast({
								title: '下载成功',
								icon: 'success'
							});
						} else {
							uni.showToast({
								title: '下载失败',
								icon: 'none'
							});
						}
					}
				});
			},
		}
	}
</script>

<style lang="scss">
	.video-list {

		::v-deep .u-tabs__wrapper__nav {
			justify-content: space-around !important;
		}

		.list-container {
			.video-item {
				position: relative;
				width: 100%;
				height: auto;

				.video-info {
					padding: 20rpx;
					border-radius: 10rpx;
					background-color: #f8f8f8;

					.video-title {
						font-size: 28rpx;
						color: #000;
						line-height: 1.4;
						margin-bottom: 16rpx;
					}

					.video-meta {
						display: flex;
						align-items: center;
						padding: 10rpx;

						.quality {
							font-size: 28rpx;
							color: #fff;
							padding: 4rpx 12rpx;
							border-radius: 8rpx;
						}

						.save-btn {
							font-size: 20rpx;
							background: #FF7220;
							color: #fff;
							padding: 6rpx 12rpx;
							border-radius: 32rpx;
						}
					}
				}
			}
		}

		.button-group {
			display: flex;
			justify-content: space-between;
			margin: 50rpx;
			gap: 40rpx;

			.u-button--plain {
				background: #fde4cb;
			}

			button {
				flex: 1;
				height: 80rpx;
				line-height: 80rpx;
				font-weight: 400;
				font-family: PingFangSC, PingFang SC;
				font-size: 28rpx !important;
				border: none !important;
			}


		}

		.image-info {
			margin-bottom: 20rpx;

			.info-text {
				font-size: 24rpx;
				color: #666;
			}

			.watermark-info {
				display: flex;
				align-items: center;
				margin-top: 10rpx;

				.info-text {
					margin-left: 6rpx;
					color: #19be6b;
				}
			}
		}

		.image-grid {
			width: 100%;
			display: flex;
			justify-content: space-around;
			flex-wrap: wrap;

			.image-item {
				width: 180rpx;
				padding: 20rpx;

				.grid-image {
					width: 180rpx;
					height: 180rpx;

				}

			}
		}



	}
</style>